package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/12/9 10:10
 * @description：https://leetcode-cn.com/problems/valid-tic-tac-toe-state/
 */
public class 有效的井字游戏 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.validTicTacToe(new String[]{"XXX", "OOX", "OOX"}));
    }

    class Solution {
        public boolean validTicTacToe(String[] board) {
            int countX = 0, countO = 0;
            char[][] map = new char[3][3];
            int idx = 0;
            // 计算X和O的数量
            for (String s : board) {
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    if (c == 'X') countX++;
                    else if (c == 'O') countO++;
                    map[idx][i] = c;
                }
                idx++;
            }
            // 游戏的基本条件
            if (countX < countO || countX > countO + 1) return false;
            boolean isXWin = false, isOWin = false;
            // 判断对角线
            if (map[1][1] != ' ' && ((map[0][0] == map[1][1] && map[2][2] == map[1][1])
                    || (map[0][2] == map[1][1] && map[2][0] == map[1][1]))) {
                if (map[1][1] == 'X') {
                    isXWin = true;
                } else {
                    isOWin = true;
                }
            }
            // 判断每行每列
            for (int i = 0; i < 3; i++) {
                if (map[i][0] != ' ' && map[i][0] == map[i][1] && map[i][1] == map[i][2]) {
                    if (map[i][0] == 'X') {
                        // if (isXWin) return false;
                        isXWin = true;
                    } else if (map[i][0] == 'O') {
                        // if (isOWin) return false;
                        isOWin = true;
                    }
                }
                if (map[0][i] != ' ' && map[0][i] == map[1][i] && map[1][i] == map[2][i]) {
                    if (map[0][i] == 'X') {
                        // if (isXWin) return false;
                        isXWin = true;
                    } else if (map[0][i] == 'O') {
                        // if (isOWin) return false;
                        isOWin = true;
                    }
                }
            }
            // 如果X赢了，X的数量一定大于O
            if (isXWin && countO == countX) return false;
            // 如果O赢了，X的数量一定等于O
            if (isOWin && countO < countX) return false;
            return !isOWin || !isXWin;
        }
    }
}
